package ipebg.mzk.provider.system.service.impl;

import ipebg.mzk.facade.entity.MsAdminFunction;
import ipebg.mzk.facade.entity.MsAdminUser;
import ipebg.mzk.facade.system.bean.MenuTreeBean;
import ipebg.mzk.facade.system.service.FunctionService;
import ipebg.mzk.facade.system.service.MenuService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("menuServiceImpl")
public class MenuServiceImpl implements MenuService {
	private static Log log = LogFactory.getLog(MenuServiceImpl.class);
	@Resource(name = "functionServiceImpl")
	private FunctionService functionServiceImpl;

	/**
	 * 按照List中的某个String类型的属性进行排序
	 * 
	 * @param list
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void sortStringMethod(List list) {
		Collections.sort(list, new Comparator() {
			@Override
			public int compare(Object o1, Object o2) {
				MsAdminFunction stu1 = (MsAdminFunction) o1;
				MsAdminFunction stu2 = (MsAdminFunction) o2;
				return stu1.getFunctionCode().compareTo(stu2.getFunctionCode());
			}
		});
	}

	private List<MenuTreeBean> buildMenuTree(List<MsAdminFunction> menuList, String parentId, String name) {
		List<MenuTreeBean> list = new ArrayList<MenuTreeBean>();
		for (MsAdminFunction fc : menuList) {
			if (fc.getParentId().equals(parentId)) {
				MenuTreeBean bean = new MenuTreeBean();
				if (fc.getParentId().equals("00")) {
					bean.setProject(fc.getFunctionName());
				} else {
					bean.setProject(name);
				}
				bean.setId(fc.getFunctionId());
				bean.setUrl(fc.getFunctionUrl());
				bean.setChecked(false);
				bean.setText(fc.getFunctionName());
				bean.setChildren(buildMenuTree(menuList, fc.getFunctionId(), bean.getProject()));
				list.add(bean);
			}
		}
		return list;
	}

	@Transactional(readOnly=true)
	public List<MenuTreeBean> menuList(MsAdminUser user) {

		List<MsAdminFunction> functionList = new ArrayList<MsAdminFunction>();
		try {
			functionList = functionServiceImpl.findFunctionListByUserId(user.getAdminId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sortStringMethod(functionList);
		return buildMenuTree(functionList, "00", null);
	}
}
